package com.yayako.utils.common;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextUtil implements ApplicationContextAware, DisposableBean {
  private static ApplicationContext applicationContext;

  public static <T> T getBean(Class<T> clazz) {
    return applicationContext.getBean(clazz);
  }

  private static void clear() {
    applicationContext = null;
  }

  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    ApplicationContextUtil.applicationContext = applicationContext;
  }

  @Override
  public void destroy() throws Exception {
    ApplicationContextUtil.clear();
  }
}
